package com.hyving.summer.fxexcel.ctrl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.hyving.summer.fxexcel.model.GoodsCount;
import com.hyving.summer.fxexcel.model.GoodsTableView;
import com.hyving.summer.fxexcel.model.SourceOrder;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Pane;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class MainCtrl implements Initializable {

    public Pane rootPane;

    public Button btnChooseFile;

    public TableView<GoodsTableView> table;

    public TableColumn num;
    public TableColumn name;
    public TableColumn sale;
    public TableColumn refund;
    public TableColumn rate;


    public void initialize(URL location, ResourceBundle resources) {
        log.info("initialize: {}", location.getPath());
    }

    public void onBtnChooseFileClick(ActionEvent actionEvent) {
        Window window = rootPane.getScene().getWindow();
        FileChooser fileChooser = new FileChooser();
        // 文件类型过滤器
        /*FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Excel files (*.xls, *.xlsx)", "*.xls", "*.xlsx");
        fileChooser.getExtensionFilters().add(filter);*/
        // ...
        File file = fileChooser.showOpenDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();

//        if (file != null) {
//            Alert alert = new Alert(Alert.AlertType.INFORMATION);
//            alert.setContentText("文件路径：" + fileAbsolutePath);
//            alert.show();
//        }
//        ObservableList<GoodsTableView> list = FXCollections.observableArrayList();
//        list.add(new GoodsTableView(1,"12",2,0,0.00));
//        list.add(new GoodsTableView(2,"23",1,1,100.00));
        ObservableList<GoodsTableView> list = parseFile(file);

        num.setCellValueFactory(new PropertyValueFactory<GoodsTableView,Integer>("num"));
        name.setCellValueFactory(new PropertyValueFactory<GoodsTableView,String>("name"));
        sale.setCellValueFactory(new PropertyValueFactory<GoodsTableView,Integer>("sale"));
        refund.setCellValueFactory(new PropertyValueFactory<GoodsTableView,Integer>("refund"));
        rate.setCellValueFactory(new PropertyValueFactory<GoodsTableView,Double>("rate"));

        table.setItems(list);

    }

    @SneakyThrows
    private ObservableList<GoodsTableView> parseFile(File file) {

        InputStream fileInputStream = new FileInputStream(file);

        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
//        params.setSaveUrl("/excel/");
//        params.setNeedSave(false);
        List<SourceOrder> orders = ExcelImportUtil.importExcel(fileInputStream, SourceOrder.class, params);
        System.out.println(JSON.toJSON(orders));
        System.out.println(orders.size());

        HashMap<String , GoodsCount> goodsMap =new HashMap<String , GoodsCount>();

        for(int i =0;i<orders.size();i++){
            SourceOrder s =orders.get(i);
            String goodsName =s.getGoodsName();
            String[] g =goodsName.split(" ");
            String name =g[0];
            GoodsCount goodsCount = goodsMap.get(name);
            if(goodsCount==null){
                goodsCount =new GoodsCount();
                goodsCount.setName(name);
            }


            if("已取消".equals(s.getOrderStatus())
                    ||"待配货".equals(s.getOrderStatus())
                    ||"已发货未签收".equals(s.getOrderStatus())){


            }else{
                if("售后完成".equals(s.getSaleStatus())||"售后处理中".equals(s.getSaleStatus())){
                    goodsCount.refund();
                }else{
                    goodsCount.sale();
                }
            }

            goodsMap.remove(name);
            goodsMap.put(name,goodsCount);
        }

        Set<String> keySet = goodsMap.keySet();
        List<GoodsCount> gg =new ArrayList<GoodsCount>();
        for (String key : keySet) {
            gg.add(goodsMap.get(key));

        }
        gg =gg.stream().sorted(Comparator.comparing(GoodsCount::getSaleCount,Comparator.reverseOrder())).collect(Collectors.toList());

        ObservableList<GoodsTableView> list = FXCollections.observableArrayList();
        for(int i=0;i<gg.size();i++){
            GoodsCount g =gg.get(i);
            BigDecimal rate = new BigDecimal(g.countRefund());
            double r = rate.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            list.add(new GoodsTableView(i+1,g.getName(),g.getSaleCount(),g.getRefundCount(),r));
        }

        return list;

    }
}
